package org.pentaho.di.trans.steps.abnormalcheck;


import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.i18n.BaseMessages;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author dc
 * @Type AbnormalCheckFunction.java
 * @Desc
 * @date 2022/10/19 17:42
 */
public class AbnormalCheckFunction {


    public int m_columnIndex;
    public double m_count;
    public double m_mean;

    public double m_median;
    public double m_fixed;
    public double m_sum;
    protected LogChannelInterface log;


    public double generateOutputValues(AbnormalCheckConfig config, ArrayList<Number> cache) {
        //平均值
        double calVal = 0;
        if (config.isMeanFlag()) {
            m_mean = Double.NaN;
            if (m_count > 0) {
                m_mean = m_sum / m_count;
            }
            if(config.getMultiple()>0){
                m_mean *=config.getMultiple() ;
            }

            calVal = m_mean;
        }
        //中位数
        if (cache != null) {
            if (config.isMedianFlag()) {
                double[] result = new double[(int) m_count];
                for (int i = 0; i < cache.size(); i++) {
                    result[i] = cache.get(i).doubleValue();
                }
                Arrays.sort(result);
                m_median = percentile(0.5, result);
                if(config.getMultiple()>0){
                    m_median *=config.getMultiple() ;
                }
                calVal = m_median;
            }
        }
        //固定值
        if (config.isFixedFlag()) {
            m_fixed = config.getMultiple();
            calVal = m_fixed;
        }
        return calVal;
    }

    private double percentile(double p, double[] vals) {
        double n = m_count;
        // simple method
        double i = p * n;
        double res = 0;
        if (i - Math.floor(i) > 0) {
            i = Math.floor(i);
            res = vals[(int) i];
        } else {
            res = (vals[(int) (i - 1)] + vals[(int) i]) / 2.0;
        }
        return res;
    }
}
    
